package iosr11.gbase;

import iosr11.data.Teacher;
import iosr11.data.TeacherImpl;
import iosr11.gcontacts.Contacts;

import com.google.api.gbase.client.FeedURLFactory;
import com.google.api.gbase.client.GoogleBaseEntry;
import com.google.api.gbase.client.GoogleBaseFeed;
import com.google.api.gbase.client.GoogleBaseQuery;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.contacts.ContactEntry;

public class TeacherBaseImpl implements TeacherBase{

	BaseDAO engine;
	Contacts contacts;
	public TeacherBaseImpl(BaseDAO engine, Contacts contacts){
		this.engine = engine;
		this.contacts = contacts;
	}
	
	@Override
	public boolean addNewTeacher(GoogleBaseEntry entry) {
		return engine.addRecord(entry);
	}

	@Override
	public boolean addNewTeacher(String realUserName, String email,
			boolean isLecturer) {
		String userId = contacts.addNewUserReturnId(realUserName, email);
		if (userId==null)
			return false;
		System.out.println(userId);
		GoogleBaseEntry entry = new GoogleBaseEntry();
		entry.setTitle(new PlainTextConstruct("teacher"));
		entry.setDraft(true);
		entry.getGoogleBaseAttributes().setItemType("teacher");
		entry.getGoogleBaseAttributes().addBooleanAttribute("is lecturer", isLecturer);
		entry.getGoogleBaseAttributes().addTextAttribute("user", userId);
		return this.addNewTeacher(entry);
	}

	@Override
	public void setService() {
		
	}

	@Override
	public Teacher getTeacher(String username) {
		// TODO Nie sprawdza czy teacher
		ContactEntry contact = contacts.getUser(username);
		if (contact == null)
			return null;
		String userId = contact.getId();
		
		GoogleBaseQuery query = new GoogleBaseQuery(FeedURLFactory.getDefault().getItemsFeedURL());
		GoogleBaseFeed feed = engine.getQueryResult(query, "user", userId);
		if (feed==null)
			return null;
		if (feed.getEntries().size()!=1)
			return null;
		//ArrayList<String> groups
	
		return new TeacherImpl(contact.getTitle().getPlainText(),
				contact.getEmailAddresses().get(0).getAddress(),
				null,
				feed.getEntries().get(0).getId(),
				feed.getEntries().get(0).getGoogleBaseAttributes().getBooleanAttribute("is lecturer"));
	}
	
	
}
